<template>
  <div class="color-doppler pd-20">
    <el-row class="mt-20">
      <el-col :span="20">
        <el-radio-group v-model="configType"
                        @change="changeRadio">
          <el-radio-button v-for="item in listData"
                           :label="item.value"
                           :key="item.value">{{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="4"
              v-if="currentIndex === 1">
        <el-button type="primary"
                   size="mini"
                   @click="handleAdd">新增省市编码
        </el-button>
      </el-col>
    </el-row>
    <el-form :model="addForm"
             ref="addForm"
             label-width="100px"
             class="mt-20"
             v-if="currentIndex===1">
      <div class="
             mt-20">
        <div v-for="(item, index) in addForm.areaCodeDtos"
             :key="item.key"
             class="box-wrapper mt-20">
          <el-row>
            <el-col :span="7">
              <el-form-item label="选择省:"
                            :prop="'areaCodeDtos.' + index + '.baseAreaId'">
                <el-select v-model="item.baseAreaId"
                           filterable
                           :disabled="item.isShowProvince"
                           placeholder="请选择省"
                           @change="handleVal(item, index)">
                  <el-option v-for="item in provinceList"
                             :label="item.name"
                             :value="item.id"
                             :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="省统一编码:"
                            :prop="'areaCodeDtos.' + index + '.baseAreaCode'">
                <el-input class="w-200"
                          type="text"
                          v-model="item.baseAreaCode"
                          show-word-limit
                          placeholder="请输省入统一编码">

                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="三级医院收费:"
                            :prop="'areaCodeDtos.' + index + '.charge'">
                <el-input class="w-200"
                          type="text"
                          v-model="item.tertiaryHospitalFee"
                          show-word-limit
                          placeholder="请输入三级医院收费">

                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="3">
              <el-button type="danger"
                         @click="removeForm(item)">删 除
              </el-button>
            </el-col>
          </el-row>

          <ul class="city-box">
            <li v-for="list in item.areaCodeDtos"
                :key="list.baseAreaId"
                class="city-item">
              <div>
                <label style="min-width:100px;">{{ list.name }}:</label>
                <el-input v-model="list.baseAreaCode"
                          type="text"
                          v-if="list.isShow"
                          :placeholder="`请输入${list.name}统一编码`"
                          style="width: 160px"></el-input>

                <el-input v-model="list.tertiaryHospitalFee"
                          type="text"
                          v-if="list.isShow"
                          :placeholder="`${list.name}收费`"
                          style="width: 100px"></el-input>
              </div>
            </li>
          </ul>
        </div>
        <el-form-item>
          <div class="mt-20 submit-btn">
            <el-button type="primary"
                       @click="submitForm('addForm')">保 存
            </el-button>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <el-form v-if="currentIndex === 2"
             class="mt-20"
             :model="videoForm"
             :rules="videoRules"
             ref="videoRef"
             label-width="100px">
      <el-form-item label="视频地址"
                    prop="videoFileUrl">
        <el-upload class="avatar-uploader"
                   :action="fileUploadAction"
                   :on-progress="uploadVideoProcess"
                   :on-success="uploadSuccess"
                   :before-upload="beforeUploadVideo"
                   :show-file-list="false"
                   :limit="1">
          <video v-if="videoForm.videoFileUrl !='' && !videoFlag"
                 :src="videoForm.videoFileUrl"
                 class="avatar video-avatar"
                 controls="controls">
            您的浏览器不支持视频播放
          </video>
          <i v-else-if="videoForm.videoFileUrl ==='' && !videoFlag"
             class="el-icon-plus avatar-uploader-icon"></i>
          <el-progress v-if="videoFlag == true"
                       type="circle"
                       :percentage="videoUploadPercent"
                       style="margin-top:7px;"></el-progress>

        </el-upload>
        <p class="Upload_pictures">
          <span></span>
          <span>最多可以上传1个视频，大小不超过50M，推荐格式mp4</span>
        </p>
      </el-form-item>
      <el-button type="primary"
                 @click="saveVideoAction"
                 :disabled="isSave">保 存
      </el-button>
    </el-form>
  </div>
</template>
<script>
export default {
  name: 'colorDoppler', // 彩超配置
  data() {
    return {
      type: 'color',
      configType: 1,
      currentIndex: 1,
      listData: [
        {label: '收费编码配置', value: 1},
        {label: '视频地址配置', value: 2}
      ],
      addForm: {
        baseAreaCode: '', // 全国统一编码
        tertiaryHospitalFee:'',//三级医院收费标准
        areaCodeDtos: [
          {
            baseAreaId: '', // 省ID
            baseAreaCode: '', // 省统一编码
            tertiaryHospitalFee:'',//三级医院收费标准
            areaCodeDtos: [
              {
                baseAreaId: '', // 市ID
                baseAreaCode: '', // 市统一编码
                tertiaryHospitalFee:'',//三级医院收费标准
              }
            ]
          }
        ]
      },
      provinceList: [],
      isShow: false,
      isShowProvince: false,
      videoFlag: false,
      // 是否显示进度条
      videoUploadPercent: '',
      // 进度条的进度，
      isShowUploadVideo: false,
      // 显示上传按钮
      videoForm: {
        videoFileUrl: '',
      },
      videoRules: {
        videoFileUrl: [
          {required: true, message: '请上传视频', trigger: 'blur'},
        ]
      },
      isSave: false,

      fileUploadAction: this.api.appUpgradeUpload.url,
    }
  },
  methods: {
    // 选择
    changeRadio(val) {
      this.currentIndex = val
      if (val === 1) {
      }
      if (val === 2) {
        this.showVideo() // 视频详情
      }
    },
    // 提交事件
    submitForm(formName) {
      let res = this.addForm.areaCodeDtos
      if (res.length > 0) {
        let item = res[res.length - 1]
        if (item.baseAreaId === '') {
          this.$message.error('请选择省');
          return
        }
        if (item.baseAreaCode === '') {
          this.$message.error('请填写省统一编码');
          return
        }
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          /* this.addForm.areaCodeDtos.map(item => {
            item.areaCodeDtos = item.areaCodeDtos.filter(e => e.baseAreaCode != '')
            return item
          }); */
          const {data: res} = await this.post(this.api.codeConfig.updateServiceChargeCode, {
            code: this.type,
            ...this.addForm
          })

          if (res.code === '200') {
            this.$message.success('保存成功')
            this.getServiceChargeCode()
          } else {
            this.$message.error(res.message)
          }
        }
      });
    },
    // 重置事件
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 添加表单项事件
    handleAdd() {
      this.getChildrenArea()
      let res = this.addForm.areaCodeDtos
      if (res.length > 0) {
        let item = res[res.length - 1]
        if (item.baseAreaId === '') {
          this.$message.error('请选择省');
          return
        }
        if (item.baseAreaCode === '') {
          this.$message.error('请填写省统一编码');
          return
        }
        this.addForm.areaCodeDtos.push({
          baseAreaId: '',
          baseAreaCode: '',
          areaCodeDtos: [
            {
              baseAreaId: '', // 市ID
              baseAreaCode: '' // 市统一编码
            }
          ],
        });
      } else {
        this.addForm.areaCodeDtos.push({
          baseAreaId: '',
          baseAreaCode: '',
          areaCodeDtos: [
            {
              baseAreaId: '', // 市ID
              baseAreaCode: '' // 市统一编码
            }
          ],
        });
      }

    },
    // 移除表单项事件
    removeForm(item) {
      var index = this.addForm.areaCodeDtos.indexOf(item)
      if (index !== -1) {
        this.addForm.areaCodeDtos.splice(index, 1)
      }
    },

    // 选择省
    async getChildrenArea() {
      const {data: res} = await this.post(this.api.codeConfig.getChildrenArea, {
        id: 0
      })
      if (res.code === '200') {
        this.provinceList = res.object
      } else {
        this.$message.error(res.message)
      }
    },
    // 下拉
    async handleVal(item, index) {
      const {data: res} = await this.post(this.api.codeConfig.getChildrenArea, {
        id: item.baseAreaId
      })
      if (res.code === '200') {
        this.addForm.areaCodeDtos[index].baseAreaId = item.baseAreaId
        this.addForm.areaCodeDtos[index].areaCodeDtos = res.object.map(({
                                                                          id,
                                                                          name
                                                                        }) => ({
          baseAreaId: id,
          name,
          isShow: true,
          baseAreaCode: ''
        }))

      } else {
        this.$message.error(res.message)
      }

    },
    // 详情
    async getServiceChargeCode() {
      const {data: res} = await this.post(this.api.codeConfig.getServiceChargeCode, {
        code: this.type
      })
      if (res.code === '200') {
        // 无详情 则是添加, true 则是详情
        if (res.object) {
          let resData = res.object
          if (resData.areaCodeDtos) {
            this.addForm = resData
            this.addForm.areaCodeDtos.map(item => {
              item.isShowProvince = true
              item.areaCodeDtos.forEach(e => {
                e.isShow = true
                e['name'] = e.areaName
              })
            });
          }

        } else {
          // this.$message.error(`请添加 [${this.codeConfigInfo.name}] 全国统一编码`)
        }
      } else {
        this.$message.error(res.message)
      }
    },
    // 上传前回调
    beforeUploadVideo(file) {
      var fileSize = file.size / 1024 / 1024 < 50;
      if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!fileSize) {
        this.$message.danger("视频大小不能超过50MB");
        return false;
      }
      this.isShowUploadVideo = false;
    },
    // 上传成功回调
    uploadSuccess(response, file, fileList) {
      if (response.code === '200') {
        // 状态码为200时则上传成功
        this.isShowUploadVideo = true;
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        this.videoForm.videoFileUrl = file.response.object[0]
        this.$message.success('视频上传成功');
      } else {
        this.$message.error(response.message);
        // 状态码不是200时上传失败 从列表中删除
        fileList.splice(fileList.indexOf(file), 1);
      }
    },

    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      // this.videoUploadPercent = file.percentage.toFixed(0) * 1;
      this.videoUploadPercent = Math.floor(event.percent)
    },

    // 保存视频
    saveVideoAction() {
      this.$refs['videoRef'].validate(async (valid) => {
        if (valid) {
          const {data: res} = await this.post(this.api.codeConfig.uploadColorOperateVideoUrl, {
            code: this.type,
            operateVideoUrl: this.videoForm.videoFileUrl
          })
          if (res.code === '200') {
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },
    // 视频详情
    async showVideo() {
      const {data: res} = await this.post(this.api.codeConfig.getColorOperateVideoUrl, {
        code: this.type
      })
      console.log(res)
      if (res.code === '200') {
        this.videoForm.videoFileUrl = res.object.color
      } else {
        this.$message.error(res.message)
      }
    }
  },
  created() {
    this.getChildrenArea() // 添加
    this.getServiceChargeCode() // 详情
  }
}
</script>

<style scoped lang="scss">
.box-wrapper {
  padding: 20px 0;
  min-height: 150px;
  border: 1px solid #dcdfe6;

  .del-btn {
    margin-left: 20px;

    span {
      padding-left: 5px;
    }
  }
}

.city-box {
  display: flex;
  flex-wrap: wrap;

  .city-item {
    display: flex;
    justify-content: space-around;
    width: 33%;
    margin-bottom: 10px;

    p {
      text-align: right;

      label {
        display: inline-block;
        margin-right: 10px;
        min-width: 100px;
      }
    }
  }
}

.submit-btn {
  text-align: center;
}

.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
